package middleware

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"time"
	"zorm-learn/app/util"
)

// GinLogger 接收gin框架默认的日志
func GinLogger(logger *zap.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery
		c.Next()

		cost := time.Since(start)
		logger.Info(path,
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
			zap.Duration("cost", cost),
		)
	}
}

// GinRecovery recover掉项目可能出现的panic
/*func GinRecovery(logger *zap.Logger, stack bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// Check for a broken connection, as it is not really a
				// condition that warrants a panic stack trace.
				var brokenPipe bool
				if ne, ok := err.(*net.OpError); ok {
					if se, ok := ne.Err.(*os.SyscallError); ok {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}

				httpRequest, _ := httputil.DumpRequest(c.Request, false)
				if brokenPipe {
					logger.Error(c.Request.URL.Path,
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
					// If the connection is dead, we can't write a status to it.
					_ = c.Error(err.(error))
					c.Abort()
					return
				}

				if stack {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
						zap.String("stack", string(debug.Stack())),
					)
				} else {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
				}
				c.AbortWithStatus(http.StatusInternalServerError)
			}
		}()
		c.Next()
	}
}*/
func InitLogger(logLevel string) {

	encoder := getEncoder()
	writeSyncer := getLogWriter()
	var l zapcore.Level
	switch logLevel {
	case "INFO":
		l = zapcore.InfoLevel
		break
	case "DEBUG":
		l = zapcore.DebugLevel
		break
	case "WARN":
		l = zapcore.WarnLevel
		break
	default:
		l = zapcore.InfoLevel
	}
	core := zapcore.NewCore(encoder, writeSyncer, l)
	// 创建一个新的console WriteSyncer
	consoleWriter := zapcore.AddSync(os.Stdout)
	// 创建控制台日志的核心
	consoleCore := zapcore.NewCore(
		encoder,
		consoleWriter,
		zap.NewAtomicLevelAt(zap.InfoLevel),
	)
	// 将两个核心合并
	cores := []zapcore.Core{core, consoleCore}
	// 创建最终的logger
	logger := zap.New(zapcore.NewTee(cores...))
	util.MainCtx.Logger = logger

	zap.NewProductionConfig()
}

func getEncoder() zapcore.Encoder {
	// 得到编码配置
	encoderConfig := zap.NewProductionEncoderConfig()
	// 通过配置修改时间编码规则
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	// 通过配置添加调用者信息
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func getLogWriter() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "./logs/gin.log",
		MaxSize:    1,
		MaxBackups: 5,
		MaxAge:     30,
		Compress:   false,
	}
	return zapcore.AddSync(lumberJackLogger)
}
